package com.study.demo.schduleTask;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.study.demo.dto.Info;
import com.study.demo.repository.InfoRepository;
import com.study.demo.repository.PosRepository;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;

@Component
public class Task3 {
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private InfoRepository infoRepository;
    @Autowired
    private PosRepository posRepository;

    @Value("${loader.rabbitmq.queue}")
    private String queue;

    //@Scheduled(cron = "*/1 * * * * ?")
    @Transactional
    @RabbitListener(queues = "springboot.queue")
    public void consumer(Message msg) throws IOException {
        byte[] body = msg.getBody();
        ObjectMapper objectMapper = new ObjectMapper();
        Info info = objectMapper.readValue(body, Info.class);
        infoRepository.updateFlagById(info.getId());
        System.out.println(info);
//        Object object = rabbitTemplate.receiveAndConvert(queue);
//        if (object == null) {
//            return;
//        }
//        ObjectMapper objectMapper = new ObjectMapper();
//        String objJson = objectMapper.writeValueAsString(object);
//        Info info = objectMapper.readValue(objJson, Info.class);
//        infoRepository.updateFlagById(info.getId());
//        System.out.println(info.getId());
    }
}
